package com.alibaba.dubbo.governance.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.DisposableBean;

import com.alibaba.dubbo.governance.service.ZookeeperService;

/**
 * @author xuchangyue
 */
public class ZookeeperServiceImpl implements ZookeeperService, DisposableBean {

    private static final String DUBBO_PARAMS_ROOT = "/dubboRest/";
    private static final int TIMEOUT_DEFAULT = 50000;

    private ZkClient zkClient;

    private String zkAddress;

    public void setZkAddress(String address) {
        this.zkAddress = (address == null ? "" : address.split("//")[1]);
        System.out.println(zkAddress);

        if (zkAddress.length() > 0) {
            this.init(zkAddress);
        }
    };

    public String getZkAddress() {
        return zkAddress;
    }

    public void init(String zkAddress) {
        zkClient = new ZkClient(zkAddress, TIMEOUT_DEFAULT);
    }

    public void update(String path) {
        deleteRecursive(path);
        create(path);
    }

    public void create(String path) {
        create(DUBBO_PARAMS_ROOT + path, false);
    }

    public void create(String path, boolean ephemeral) {
        int i = path.lastIndexOf('/');
        if (i > 0) {
            create(path.substring(0, i), false);
        }
        if (ephemeral) {
            createEphemeral(path);
        } else {
            createPersistent(path);
        }
    }

    public void createPersistent(String path) {
        zkClient.createPersistent(path, true);
    }

    public void createEphemeral(String path) {
        zkClient.createEphemeral(path);
    }

    public void deleteRecursive(String path) {
        path = DUBBO_PARAMS_ROOT + path;
        int i = path.lastIndexOf('/');
        if (i > 0) {
            zkClient.deleteRecursive(path.substring(0, i));
        }
    }

    public void delete(String path) {
        zkClient.delete(DUBBO_PARAMS_ROOT + path);
    }

    public List<String> getChildren(String path) {
        List<String> children = new ArrayList<String>();
        if (exists(path)) {
            children = zkClient.getChildren(DUBBO_PARAMS_ROOT + path);
        }
        return children;
    }

    public boolean exists(String path) {
        return zkClient.exists(DUBBO_PARAMS_ROOT + path);
    }

    @Override
    public void destroy() throws Exception {
        zkClient.close();
    }
}
